package com.example.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/7/28 14:14
 */
@RestController
@Slf4j
public class IndexController {
    @Autowired
    private Scheduler scheduler;

    @GetMapping("/index")
    public void index() {
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/8 * * * * ?");
        TriggerKey triggerKey = TriggerKey.triggerKey("cj", "123");
        CronTrigger triggerOld = null;
        try {
            triggerOld = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (triggerOld == null) {
                JobDetail jobDetail = JobBuilder.newJob(UploadTask.class).withIdentity("cj", "123").build();
                Trigger trigger = TriggerBuilder.newTrigger().withIdentity("cj", "123")
                        .withSchedule(cronScheduleBuilder).build();
                // 执行任务
                scheduler.scheduleJob(jobDetail, trigger);
            } else {
                log.info("当前 job 已存在");
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

}
